package cn.unknowpupil.init.async;

import cn.unknowpupil.init.thread.Threads;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;
import java.util.TimerTask;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * Created at 2020/10/20 by w10g <br>
 * Initialize AsyncManager ... <br>
 * 异步任务管理器
 *
 * @author unknowpupil
 * @since 0.0.1
 */
@Slf4j
@Component
public class AsyncManager {
    /**
     * 操作延迟10毫秒
     */
    private final int OPERATE_DELAY_TIME = 10;

    @Autowired
    ScheduledExecutorService scheduledExecutorService;


    /**
     * 执行任务
     *
     * @param task 任务
     */
    @Async
    public void execute(TimerTask task) {
        System.out.println("异步");
        scheduledExecutorService.schedule(task, OPERATE_DELAY_TIME, TimeUnit.MILLISECONDS);
    }

    /**
     * 停止任务线程池
     */
    @PreDestroy
    public void shutdown() {
        log.info("====关闭后台任务任务线程池====");
        Threads.shutdownAndAwaitTermination(scheduledExecutorService);
    }
}
